<?php 
$u = empty($_REQUEST['u'])?'':trim($_REQUEST['u']);
if (empty($u)) {
    exit();
}
$u = str_replace('/', '', $u);
if (!preg_match('/^[0-9a-z.]+$/', $u, $ma)) {
    echo 'No';
    exit();
}
$filename = 'product_img/'.$u;
$info = pathinfo($filename); 
$extension = strtolower($info['extension']);

$cache_dir = '/opt/www/img_cache/';
$name_hash = md5($_SERVER['HTTP_HOST'].'_'.$_SERVER['REQUEST_URI']);

$cache_file_name = $cache_dir.$name_hash.'.jpg';
if (file_exists($cache_file_name)){
	$cache_file = @file_get_contents($cache_file_name);
	if (!empty($cache_file)) {
		output_header();
		echo $cache_file;
		exit();
	}
}

if (!file_exists($filename)){
	exit;
}

$target_width = $width = 225;
$target_height = $height = 225;

if($extension == "jpg" || $extension == "jpeg" || $extension == "JPG"){ 
  $image=imagecreatefromjpeg($filename); 
}  else if($extension == "png") { 
  $image=imagecreatefrompng($filename); 
} else if($extension == "gif") { 
  $image=imagecreatefromgif($filename); 
} else {
  exit();
}

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

if ($width && ($width_orig < $height_orig)) {
    $width = ($height / $height_orig) * $width_orig;
} else {
    $height = ($width / $width_orig) * $height_orig;
}

// Resample
$image_p = imagecreatetruecolor($target_width, $target_height);
$white = imagecolorallocate($image_p, 255, 255, 255);
imagefilledrectangle($image_p, 0, 0, $target_width, $target_height, $white);

$dst_x = intval(abs($target_width-$width)/2);
$dst_y = intval(abs($target_height-$height)/2);

imagecopyresampled($image_p, $image, $dst_x, $dst_y, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, $cache_file_name, 95);
$cache_file = @file_get_contents($cache_file_name);
if (!empty($cache_file)) {
	output_header();
    echo $cache_file;
    exit();
}


function output_header(){
	header('Content-type: image/jpeg');
	$maxage = 365*24*60*60 ;
	$expire = strftime("%a, %d %b %G %H:%M:%S GMT+8",time()+$maxage);
	header("Expires: ".$expire);
	header("Cache-Control:max-age=$maxage");
	$lastmodify = strftime("%a, %d %b %G %H:%M:%S GMT+8", strtotime('2010-01-01'));
	header('Last-Modified: ' .$lastmodify);
}
